<template>
  <TableBody>
    <template #header>
      <TableHeader ref="tableHeaderRef" :show-filter="false">
        <template #top-right>
          开始时间：<MyDatePicker4Date  v-model:time="startTime" ></MyDatePicker4Date>
          结束时间：<MyDatePicker4Date  v-model:time="endTime" ></MyDatePicker4Date>
          <AddButton @add="onAddItem"></AddButton>
        </template>
      </TableHeader>
    </template>
    <template #default>
      <n-data-table
          :loading="table.tableLoading.value"
          :data="table.dataList.value as Array<object>"
          :row-key="rowKey"
          :columns="tableColumns"
          :scroll-x="500"
          :style="{ height: `${table.tableHeight.value*2.3}px` }"
          :flex-height="true"
          :row-props="rowProps"
          :pagination="{ pageSize: 5 }"
          :bordered="false"
      />
      <n-dropdown
          placement="bottom-start"
          trigger="manual"
          :x="xRef"
          :y="yRef"
          :options="options"
          :show="showDropdownRef"
          :on-clickoutside="onClickoutside"
          @select="handleSelect"
      />
    </template>
  </TableBody>
  <TaskLogEditDrawer v-model="formData"></TaskLogEditDrawer>
</template>


<script lang="ts">
import {TableActionModel, usePagination, useRenderAction, useRowKey, useTable, useTableColumn} from "@/hooks/table";
import {
  DataTableColumn,
  FormProps, MenuOption,
  NAvatar,
  NDrawer,
  NInput, NTag, NText,
  NTime,
  SelectOption,
  useDialog,
  useMessage
} from "naive-ui";
import {post, Response} from "@/api/http";
import {
  addLifeModeItems,
  addStage, addTaskLog,
  changeGoalState,
  changeLifeModeItemsOrder,
  changeStageOrder,
  changeStageState,
  changeTaskOrder,
  changeTaskState,
  deleteStage,
  deleteTask, finishTask,
  getFieldSelect,
  getGoalSelect,
  getStageById,
  getStagesList,
  getTableList, getTaskLogList, getTaskPanelInfo,
  getTasksList, startTaskRecord
} from "@/api/url";
import {defineComponent, h, onMounted, ref, watch, defineProps, nextTick, reactive, onBeforeMount} from "vue";
import {renderSelect, renderTag, renderTimePicker, renderTreeSelect,renderIcon} from "@/hooks/form";
import GoalTree from "@/views/field/goal/GoalTree.vue";
import useUserStore from "@/store/modules/user";
import UseSurfaceSettingStore from "@/store/modules/surfaceSetting";
import { DataFormType, ModalDialogType, FormItem } from '@/types/components'
import {TreeSelectOption} from "naive-ui/lib/tree-select/src/interface";
import { Book } from "@vicons/ionicons5";
import {UseConstsStore} from "@/store/modules/consts";
import pinia from "@/store/pinia";
import {changeTimeUnit, getWeek, obj2Map} from "@/utils";
import Sortable from "sortablejs";
import {TimeMentionModal, TaskData, StageData, TaskPanel, TaskMoreData, TaskLogData} from "@/views/model/model";
import TaskEditDrawer from "@/views/task/TaskEditDrawer.vue";
import MyTime from "@/views/task/time/MyTime.vue";
import GoalPanel from "@/views/field/goal/GoalPanel.vue";
import AddButton from "@/components/common/AddButton.vue";
import TaskLogEditDrawer from "@/views/taskoperation/tasklog/TaskLogEditDrawer.vue";
import MyDatePicker from "@/views/task/time/MyDatePicker.vue";
import MyDatePicker4Date from "@/views/task/time/MyDatePicker4Date.vue";

export default defineComponent({
  name: 'TaskLogList',
  components: {MyDatePicker4Date, MyDatePicker, TaskLogEditDrawer, AddButton, GoalPanel, NDrawer},
  props:{
    index:Number,
    PanelName:String,
    type:Number
  },
  setup(props) {
    const key = ref<number>(new Date().getTime())
    const table = useTable()
    const rowKey = useRowKey('id')
    const naiveDialog = useDialog()
    const message = useMessage()
    const userStore = useUserStore()
    const useSurfaceSetting = UseSurfaceSettingStore()
    const useConsts = UseConstsStore()
    // const pagination = usePagination(doRefresh)
    const checkedRowKeys = [] as Array<any>

    const startTime = ref(Date.now())
    const endTime = ref(Date.now())

    const surfaceSetting = useSurfaceSetting.getSurfaceSetting();
    const satgeMenuOptions = useConsts.getLabelValue(useConsts.getConsts().panelStateMap)
        .map(u=>{return {...u,icon:renderIcon(Book),key:u.value}})
    let dataInfo = new Map();
    const taskTypes = obj2Map(useConsts.getConsts().taskTypeMap)
    const taskLogTypes = obj2Map(useConsts.getConsts().taskLogTypeMap)

    const updateState = (key: string, item: MenuOption)=>{
      // 重新获取数据
      surfaceSetting.showTaskPanelState = key
      console.log(key)
      table.dataList.value = dataInfo.get(surfaceSetting.showTaskPanelState)
    }

    // 表单处理
    const tableColumns = useTableColumn(
        [
          // table.selectionColumn,
          // table.indexColumn,
          {
            title: 'id',
            key: 'id',
          },
          {
            title: '任务名',
            key: 'taskName',
          },
          {
            title: '任务类型',
            key: 'type',
            render: (rowData:any) => {
              // console.log("+++++++++++++",taskLogTypes,taskTypes)
              // console.log("+++++++++++++",taskTypes.get(rowData.taskType.toString()),taskLogTypes.get(rowData.taskLogType.toString()))
              const label = taskTypes.get(JSON.stringify(rowData.taskType))?taskTypes.get(JSON.stringify(rowData.taskType)):'生活';
              return [renderTag(taskLogTypes.get(rowData.taskLogType.toString()), {size: 'small',}),
                renderTag(label, {size: 'small',})]
            }
          },
          {
            title: '阶段',
            key: 'stageName',
          },
          {
            title: '领域',
            key: 'fieldName',
          },
          {
            title: '目标',
            key: 'goalName',
          },
          {
            title: '开始时间',
            key: 'startTime',
            render: (rowData) => {
              return h(MyTime,{
                time:rowData.startTime,
                type:"datetime"
              },{})
            }
          },
          {
            title: '结束时间',
            key: 'endTime',
            render: (rowData:any) => {
              return h(MyTime,{
                time:rowData.endTime,
                type:"datetime"
              },{})
            }
          },
          {
            title: '所花时间',
            key: 'takeTime',
            render: (rowData:any) => {
              return h(NText,{},{
                default: () => changeTimeUnit(rowData.endTime-rowData.startTime),
              })
            }
          },
        ],
        {
          align: 'center',
        } as DataTableColumn
    )

    // 加载数据
    async function doRefresh() {
      // await getInfoFromBack()
      // 获取阶段的信息
      // console.log("++++++++++++++++",info.data.tasks)
      // console.log({taskIds:taskIds,finishStageId:finishStageId})
      // endTime.value = endTime.value>startTime.value?endTime.value:startTime.value+100
      post({
        url: getTaskLogList,
        data: {startTime:startTime.value, endTime: endTime.value},
        token:userStore.getToken()
      }).then(async (res: Response) => {
        // console.log(res.data.data)
        // if(res.data.data) dataInfo = obj2Map(res.data.data)
        await table.handleSuccess(res.data)
        // console.log(table.dataList)
      }).catch(console.log)
      if(table.dataList.value) table.dataList.value=[];
      table.tableLoading.value = false
      // console.log(table.dataList.value)

    }
    onMounted(doRefresh)
    // 添加/编辑框
    const formData = reactive({
      show:false,
      key:Date.now(),
      data:TaskLogData.getNewTaskLogData()
    })
    watch(formData,async ()=>{
      // console.log(formData.key, key.value)
      if(formData.key !== key.value){
        // await getInfoFromBack()
        // await doRefresh()
        key.value = Date.now()
      }
    })
    watch(key, async ()=>{
      // console.log(key,"+++++++++++++")
      // await getInfoFromBack()
      await doRefresh()
      formData.key= key.value
    })
    watch(startTime, doRefresh)
    watch(endTime, doRefresh)

    // 删除添加
    function onAddItem(type:number) {
      formData.data = TaskLogData.getNewTaskLogData()
      formData.show = true
    }
    function onUpdateItem(item: TaskLogData|null) {
      if(item){
        formData.data = item
        console.log(formData.data)
        formData.show = true
      }
    }
    function onDeleteItem(item: any) {
      naiveDialog.warning({
        title: '提示',
        content: '确定要删除此数据吗？',
        positiveText: '确定',
        onPositiveClick: async () => {
          table.dataList.value!.splice(table.dataList.value!.indexOf(item), 1)
          try {
            const data: Response = await post({
              url: addTaskLog,
              data: {...item,toAdd:2},
              token:userStore.getToken()
            });
            // console.log(data)
            message.success(data.msg)
          }catch(e) {
            message.error((e as Error).message)
          }finally {
          }
        },
      })
    }
    // 下来菜单
    let chooseRow:TaskLogData|null = null;
    const options = [
      {
        label: "编辑",
        key: "edit",
      },
      {
        label: () => h("span", { style: { color: "red" } }, "删除"),
        key: "delete",
      },
    ];
    const showDropdownRef = ref(false);
    const xRef = ref(0);
    const yRef = ref(0);
    const onClickoutside = () => {
      showDropdownRef.value = false;
    };
    const handleSelect = async (key: string, node: string) => {
      // console.log(key, node);
      showDropdownRef.value = false;
      if (key == "edit") {
        onUpdateItem(chooseRow)
      }
      if (key == "delete") {
        onDeleteItem(chooseRow)
      }
    };
    const rowProps = (row:TaskLogData) => {
      return {
        // 双击
        ondblclick: (e: MouseEvent) => {
          e.preventDefault()
          // message.info(JSON.stringify(row, null, 2));
          showDropdownRef.value = true;
          xRef.value = e.clientX;
          yRef.value = e.clientY;
          // console.log('rowProps',row)
          chooseRow = row
        },
        onContextmenu: (e: MouseEvent) => {
          e.preventDefault()
          // message.info(JSON.stringify(row, null, 2));
          showDropdownRef.value = true;
          xRef.value = e.clientX;
          yRef.value = e.clientY;
          // console.log('rowProps',row)
          chooseRow = row
        },
      };
    };

    function onRowCheck(rowKeys: Array<any>) {
      checkedRowKeys.length = 0
      checkedRowKeys.push(...rowKeys)
    }
    return {
      surfaceSetting,updateState,startTime,endTime,
      key,
      formData,
      xRef,yRef,options,handleSelect,onClickoutside,showDropdownRef,
      satgeMenuOptions,
      rowProps, onAddItem,
      table,
      rowKey,checkedRowKeys,onDeleteItem,
      onRowCheck,tableColumns,
      pattern: ref(''),
    }
  },
})

</script>

<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 30px;
  margin: 0 auto;
  vertical-align: middle;
  .avatar {
    width: 100%;
    border-radius: 50%;
  }
  .avatar-vip {
    border: 2px solid #cece1e;
  }
  .vip {
    position: absolute;
    top: 0;
    right: -9px;
    width: 15px;
    transform: rotate(60deg);
  }
}
.gender-container {
  .gender-icon {
    width: 20px;
  }
}
</style>